<template>
    <div class="mine">
        <el-page-header @back="$router.push('/home/index')" content="个人信息">
        </el-page-header>
        <el-divider></el-divider>
        <!-- 修改信息 -->
        <el-form :model="userInfo" :rules="userInfoRules" label-width="100px" style="max-width: 300px;">
            <el-form-item>
                <template #label>
                    <h2 style="color: black;">修改信息</h2>
                </template>
            </el-form-item>
            <el-form-item label="头像">
                <!-- 上传组件，需要手动配置接口地址和请求头信息，无法调用axios -->
                <el-upload ref="uploadRef" :action="upload.url" :headers="upload.hearders" :auto-upload="false"
                    :file-list="upload.fileList" :on-change="handleChangeFile">
                    <el-avatar :size="100">
                        <img v-if="upload.previewUrl" :src="upload.previewUrl">
                        <img v-if="upload.previewUrl === undefined" :src="'/student/v3' + userInfo.avatar">
                    </el-avatar>
                </el-upload>
            </el-form-item>
            <!-- v-model是数据双向绑定 -->
            <!-- vuex:单项数据流，数据只能由mutation修改 -->
            <el-form-item label="账号" prop="userName">
                <el-input :value="userInfo.userName" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
                <el-input v-model="userInfo.realName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
                <el-button type="info" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <!-- 修改密码 -->
        <el-form ref="passwordRef" :model="password" :rules="passwordRules" label-width="100px"
            style="max-width: 300px;">
            <el-form-item>
                <template #label>
                    <h2 style="color: black;">修改密码</h2>
                </template>
            </el-form-item>
            <el-form-item label="原密码" prop="originalPassword">
                <el-input type="password" show-password v-model="password.originalPassword"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
                <el-input type="password" show-password v-model="password.password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="requirePassword">
                <el-input type="password" show-password v-model="password.requirePassword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="changeUpdatePassword">提交</el-button>
                <el-button type="info" @click="handleResetPassword">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>

<script>
import { getToken } from '@/utils/cookie.js'
import { updateUserInfo, userInfo, updatePassword, login } from '@/api/user.js'
export default {
    name: 'Mine',
    data() {
        // 密码一致性验证规则
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            }
            else if (value === this.password.originalPassword) {
                callback(new Error('新密码与旧密码相同'));
            }
            else {
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.password.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };

        return {
            userInfo: {},
            //    用户校验
            userInfoRules: {
                userName: [{
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur',
                }],
                realName: [{
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur',
                }],
            },
            upload: {
                url: '/student/v3/prod-api/file/upload',
                hearders: {
                    Authorization: `Bearer ${getToken()}`
                },
                fileList: [],
                previewUrl: undefined,
            },
            // 用户密码
            password: {
                originalPassword: undefined,
                password: undefined,
                requirePassword: undefined,
            },
            // 密码校验
            passwordRules: {
                originalPassword: [{
                    required: true,
                    message: '请输入原密码',
                    trigger: 'blur',
                },],
                password: [{
                    required: true,
                    message: '请输入新密码',
                    trigger: 'blur',
                },
                {
                    validator: validatePass,
                    trigger: 'blur'
                }],
                requirePassword: [{
                    required: true,
                    message: '请输入确认密码',
                    trigger: ['blur', 'change'],
                }, {
                    validator: validatePass2,
                    trigger: 'blur'
                }],
            }
        }
    },
    watch: {
        // 1.异步拿到的，看有没有拿到数据 2.对象形式
        '$store.state.userInfo': {
            immediate: true,
            deep: true,
            handler(newVal) {
                const { createTime, updateTime, userId, ...rest } = newVal
                this.userInfo = JSON.parse(JSON.stringify(rest))
            },
        }
    },
    methods: {
        // 文件提交
        handleChangeFile(file, fileList) {
            // 手动同步临时存储的信息，通过file-list控制组件缓存所需要上传的文件数量，只上传最新的
            if (file.status === 'ready') {
                // 清除上一张的临时链接
                URL.revokeObjectURL(this.upload.previewUrl)
                // 图片预览
                this.upload.previewUrl = URL.createObjectURL(file.raw)
                this.upload.fileList = [file]
                console.log(this.upload.fileList)

            }
            if (file.status === 'success') {
                const { code, data } = file.response
                if (code === 200) {
                    //    获取上传的头像路径
                    this.userInfo.avatar = data.fileUrl
                    //    清空临时存储的数据
                    this.upload.fileList = []
                    // 清空预览路径
                    this.upload.previewUrl = undefined
                    //提交修改用户信息
                    this.handleSubmit()

                }
            }
        },
        // 提交
        handleSubmit() {
            if (this.upload.fileList.length > 0) {
                this.$refs['uploadRef'].submit()
                return
            }
            const { userName, ...rest } = this.userInfo
            console.log(rest)
            updateUserInfo(rest).then(res => {
                console.log(res)
                this.$message.success('上传成功')
                this.$store.dispatch('getUserInfo')
            })

        },
        // 重置
        handleReset() {
            userInfo().then(res => {

                this.userInfo.userName = res.data.userName
                this.userInfo.realName = res.data.realName
                //    清空临时存储的数据
                this.upload.fileList = []
                // 清空预览路径
                this.upload.previewUrl = undefined
                this.upload.url = `${this.upload.url}+${res.data.avatar}`

            })
        },
        //提交修改密码
        changeUpdatePassword() {
            this.$refs['passwordRef'].validate(valid => {
                console.log(valid)
                if (!valid) return
                const { originalPassword, password } = this.password
                const { userId } = this.userInfo
                updatePassword({ originalPassword, password, userId }).then(res => {
                    this.$message.success(res.msg)
                    // 清空密码表单
                    this.$refs['passwordRef'].resetFields()
                }).catch(error => {
                    this.$message.error(error.errorMsg)
                })

            })
        },
        // 重置密码表单
        handleResetPassword() {
            // 清空密码表单
            this.$refs['passwordRef'].resetFields()
        }
    }
}
</script>